define(['apps/utils/tools','apps/utils/math','apps/utils/chart'],function (tools,math,chart){
   var min = -10000,max = 10000,vaprefix = "cnbi";
   
   
   /**
    * 模型对象
    * 
    */
   var scope = this;
   scope.module = {};
  /**
   * 获取silder与progress随机数据的方法
   */
  function getRandom(min,max){
    return (math.getRandom(min,max))/100;
  }
   /**
   * 根据数组的Id随机给datas[Id]随机设值
   */
  function setRandomDatas(arr,datas){
      for (var i = 0,len = arr.length;i<len;i++) {
        	var tval = getRandom(min,max);
            datas[arr[i]["id"]] =tval;
      }
  }
  /**
   *  辅助参数设值
   *  assist_Items
   *  bjq_Items
   *  qc_Items
   */
  function setAssistParams(datas){
  	   if(scope.module["assistItems"]){
  	   	var arr = scope.module["assistItems"];
	      for (var key in arr) {
	        	 setRandomDatas(arr[key],datas);
	      }
  	   }
  }
  /**
    * 当查询失败或调试时用的初始随机数据的方法
   */
   function  initRandomData(){
   	   if(scope.module["dataType"] == "defined"){
   	       scope.module["datas"] = eval("("+scope.module["datas"]+")");
   	   }else if(scope.module["dataType"] == "random"){
   	         var sliderArr = scope.module["slider"], progressArr = scope.module["progress"];
   	    	 var datas = {};
	   	     if(sliderArr)setRandomDatas(sliderArr,datas);
	   	     if(progressArr)setRandomDatas(progressArr,datas);
	   	    //在这里可能还要考虑辅助的参数设值，到时候再加吧！//assistItems
	   	     setAssistParams(datas);
	   	     scope.module["datas"] =  datas;
   	   }else if(scope.module["dataType"] == "sql"){}
  };
     /**
     * 根据传来的Id从全局数据对象里获取数据 
     */
    function getValue(id,doubleUIFlag,datas){
      var valueTemp=0.00;
      if(id.indexOf(doubleUIFlag)==-1){
              valueTemp = datas[id];
      }else{
          if(doubleUIFlag != undefined){
             var  bj =array.split(doubleUIFlag)[0];
     	      valueTemp = datas[bj];
           }
     }
       return valueTemp;
    }
   
    /**
     * 设置dom的text
     */
    function setDomValue(id, value){
 	    if(isNaN(value)||value==Infinity)value =  0.00;
	 	var val =math.formatNumber(value,2);
	 	if(id.indexOf("span")==-1){
	 		$("#" + id).val(val);//如果不是span节点
	 	}else{
	 	   $("#" + id).text(val);//是span节点
	 	}
		$("#" + id).css("color", value < 0 ? "red" : "green");
    };
    
    /**
     * 获取进度条的值
     */
    function getProgressValue(a,values){
		var min = a.minValue, max = a.maxValue, value = 0;
		if (values > 0) {
			value = 0.5 + values / (2 * max);
			if (value > 1) {
				value = 1;
			}
		}
		if (values == 0) {
			value = 0.5;
			if (min == 0) {
				value = 0;
			}
		}
		if (values < 0) {
			value = 0.5 - Math.abs(values / (2 * min));
			if (value < 0)
				value = 0;
		}
		return value;
	}
	/**
     * 设置单个有Slider的值
     * 还有那个input
     */
     function setSliderValue(slider,valueTemp) {
        slider.setValue(valueTemp*100);	
        setDomValue(slider.id+"Idinput", valueTemp);
        
    };
    /**
     * 设置所有Slider的值
     * 还有那个input
     */
     function setAllSliderValue(sliderId) {
     		var slider = scope.module["slider"];
     		if(!slider)return ;
     		var datas =scope.module["datas"];
        	for(var i=0,len = slider.length;i<len;i++){
        	      var bean = slider[i],id = bean["id"];
                   setSliderValue(Ext.getCmp(id),datas[id]);
        	}
    };
	/**
     * 设置单个Progress的值
     */
     function setProgressValue(progress,valueTemp) {
             var   value = getProgressValue(progress,valueTemp);
                  progress.updateProgress(value, false);
                  setDomValue(progress.id+"Idspan",valueTemp);
                  updateProgressClass(progress,valueTemp);
    };
	 /**
     * 设置所有Progress的值
     */
     function setAllProgressValue() {
     	var progress = scope.module["progress"];
     	if(!progress)return ;
     	var datas =scope.module["datas"];
        var obj = null, value = 0.00;
        for (var i = 0; i < progress.length; i++) {
        	   var bean = progress[i],id = bean["id"];
               setProgressValue(Ext.getCmp(id),datas[id]);
        }
    };
    function getMinMax(bean){
    	if(!bean["min"]){
    	    bean["min"] = -100;
    	}
    	if(!bean["max"]){
    	    bean["max"] = 100;
    	}
       return {min:(bean["min"]-0)*100,max:(bean["max"]-0)*100};
    }
    /**
     * 创建 Ext.ProgressBar  doubleUIFlag
     */
    function createProgress(){
    	var id = "",name="";
    	try{
    	var array  = scope.module["progress"],datas = scope.module["datas"];
    	if(!array)return;
	       for (var i = 0; i < array.length; i++){
	       	var  temp = array[i],mm = getMinMax(temp);
	       	   id = temp["id"],name = temp["sname"];
	       	   var obj = Ext.getCmp(id);
	          if(!obj){
		           obj = new Ext.ProgressBar({value:datas[id],renderTo:id+"Id",id:id,cls:'progressBar',minValue:mm["min"],maxValue:mm["max"]});
	               tools.console("创建了进度条【"+name+id+"】");
	               setProgressValue(obj,datas[id]);
	          }
	       }
    	}catch(e){
    	   throw "创建进度条时【"+name+"】出错了！分析原因：页面根本找不到渲染的dom【"+id+"】节点！,请检查dom的Id书写是否规范！\n"+e;
    	}
    }
     /**
     * 创建slider
     */
    function createSlider() {
    try{  
    	var id = "",name="";
    	var array  = scope.module["slider"],datas = scope.module["datas"];
    	if(!array)return;
        for (var i = 0; i < array.length; i++) {
        var temp = array[i],mm = getMinMax(temp);id = temp["id"];name = temp["sname"]
     	  if(!Ext.getCmp(id)){
	           new Ext.Slider({value:datas[id],renderTo:id +"Id",id:id,anchor:'100%',increment:1,minValue:mm["min"],maxValue:mm["max"]});
	           tools.console("创建了拖动条【"+name+id+"】--minValue=="+temp["min"]+"----maxValue=="+temp["max"]);
	           setDomValue(id+"Idinput",datas[id]);
     		}
        }
	 }catch(e){
       throw "创建拖动条【"+name+"】出错！分析原因：页面根本找不到渲染的dom【"+id+"】节点！请检查dom的Id书写是否规范！\n"+e;
       return ;
	 }
    }
    /**
     * 计算公式的地方 亲！
     */
    function calcExp(formula){
       try{
       	   //formula["calcExp"] = formula["calcExp"].replaceAll("--","");
          var result =eval("("+formula["calcExp"]+")")-0;//resultExp = exp+"=="+r,
          if(isNaN(result) || result == Infinity||result == -Infinity) result=0.00;
 	       scope.module["datas"][formula.id] = result;
 	       tools.console(formula["sname"]+"=="+formula["formula"]+"=="+formula["calcExp"]+"=="+result);
 	       }catch(er){
    	      throw "name=="+formula["name"]+"--id=="+formula["id"]+"-->执行公式操作时出错：-->"+formula["formula"]+"-->"+formula["calcExp"]+"-->"+er;
         }  
    }
    function formulaOperation(formula){
    	try{
    	  var params = formula["params"],exp = formula["exp"];
	       for(var j=0;j<params.length;j++){
	   	     	if(params[j].indexOf(vaprefix) !=-1){
	   	     	   params[j]=params[j].replaceAll(vaprefix,"");//a9 1 1140  11401  
	   	     	}
	   	     	var val = getVarEval(params[j],formula);
	   	     	if(val-0 < 0){
	   	     	    val="("+val+")";
	   	     	}
	           	exp = exp.replaceAll(params[j],val);
	        }
       	     formula["calcExp"] = exp;
	         calcExp(formula);
	     }catch(e){
    	     throw formula["sname"]+"公式或者其参数配制有错！\n"+e;
    	}    
    }
    function setFormulas(formulas){
    	try{
    		   if(formulas instanceof Array){
		         for(var i = 0,len = formulas.length;i<len;i++){
		        	   formulaOperation(formulas[i]);
		         }
    		   }else{
    		     formulaOperation(formulas);
    		   }
    	}catch(e){
    	     throw "【"+scope.module["title"]+"】设置计算公式出错!\n"+e;
    	}
  }
    /**
     * 设置公式的值哦
     * db_formulas
     * assists_formulas
     * userDefined_formulas
     */
    function setFormula(){
        var  formulas = scope.module["formula"];
        if(!formulas)return;
       var  formula={},flag = false;
        for(var key in formulas){
        	  var temp = formulas[key];
             //if(key == "assists_formulas"){//有顺序问题哦亲!
                //if(formulas[key])setFormulas(formulas[key]);
             //}else if(key == "userDefined_formulas"){
             
             //}else if(key == "db_formulas"){
             //}
        	 if(temp instanceof Array){
        	    for(var i=0,len = temp.length;i<len;i++){
        	        formula[temp[i]["id"]] =temp[i];
        	        setFormulas(temp[i]);
        	        flag = true;
        	    }
        	}else{
        	   setFormulas(temp);
        	}
        }
        if(flag)scope.module["formula"] = formula;
    }
	function updateTipHtml(){
		var arr = scope.module["tips"];
		if(!arr)return ;
		for(var i=0,len =arr.length;i<len;i++){
		   var tip = arr[i],params = tip["params"],formula = tip["formula"];
		     for(var j=0,jl = params.length;j<jl;j++){
		     	 if(params[j].indexOf("_") == -1){
		            var tempValue = getVarEval(params[j], tip);
		             formula = formula.replaceAll(params[j],tempValue);
		     	 }else{//有行业参数的参数 cbfyv.bad
		     	 	    var  ps = params[j].split("_"),
		     	        ins = scope.module["industry"][ps[0]];
		     	        formula = formula.replaceAll(ps[1],ins[ps[1]]);
		     	 }
		     }
		     var fun = eval("("+formula+")");
		     var bean = fun();
		     if(bean){
		        $("#"+bean.domId).text(bean.text).addClass(bean.add).removeClass(bean.remove);
		     }
		}
	}
    /**
     * 拖动条拖动事件  除了共性的外，当然还有特殊的事情啦
     */
    function updateInputValue(id,value,datas){
        if(isNaN(value)||value==Infinity){
			value =  0.00;
			tools.console("updateInputValue----------"+id+"-------------"+scope.module.datas[id]+"不是数据！请仔细检查！");
		}
		scope.module.datas[id] = value;
        setFormula();
        setAllSliderValue();
        setAllProgressValue();
        updateTipHtml();
        /**
         * 到这里就要子类的方法了
         */
        scope.module.updataInputAfter(id,value,datas);
    }
    /**
     * 创建与更新图形组件
     * 如果bean.type 
     * type=1  单值图
     * type=2  单系列数据图
     * type=3  多系列数据图   type不同 寻找data的位置也不同的哦！
     */
    function createChart(action,bean){
      var type = bean.type;bean["chartId"] = bean["swf"] + bean["domId"] ;
       if(action){//创建
       	    if(type == 1){
       	        chart.createSingleDataChart(bean);
       	    }else if(type == 2){
       	        chart.createSingleSeriesChart(bean);
       	    }else if(type == 3){
       	        chart.createMultiSeriesChart(bean);
       	    }
       	    if(scope.module["id"] == "profita"){
        var top = "25px";
   	     if(type && type == 2){
	           top = "10px";
	     }
	     $("#"+bean["chartId"]).css("margin-top",top);
       }
       }else{//更新
       	   if(type == 1){
       	         getChartFromId(bean["chartId"]).setData(1,bean["dials"]["dial"][0]["value"]);
       	    }else if(type == 2){
       	        chart.updateChart(bean);
       	    	//chart.createSingleSeriesChart(bean);
       	    }else if(type == 3){
       	         chart.updateChart(bean);
       	    }
       }
       
    }
     /**
     * 单个Slider组件注册事件组件Id  
     */
    function initEventEveryOne(id,datas){
            var obj = Ext.getCmp(id) ;
            if(!obj){
              tools.console("没有拖动条的模型哦!亲!");
              return ;
            }
            obj.addListener("dragend", function() {
                updateInputValue(id,obj.getValue()/100,datas);
            }, this);
            obj.addListener("changecomplete", function() {
                updateInputValue(id,obj.getValue()/100,datas);
                chartOperation(false);
            }, this);
            obj.addListener("change", function() {
               // updateInputValue(id,obj.getValue()/100,datas);
            	  //chartOperation(false);
            }, this);  
    };
    /**
     * 初始事件所有
     */
    function initSliderEvent(slider,datas){
    	if(!slider)return ;
       for (var i = 0; i < slider.length; i++) {
         initEventEveryOne(slider[i]["id"],datas);
       }
    }
    
    var   reg = new RegExp(",","g");//正则表达式对象
    /**
     * input响应change事件执行的方法
     */
	function labelChange(obj){
	var 	datas = scope.module["datas"];
	  	var inputFlag = "Idinput",sliderId = (obj.id).replace(inputFlag, "");
		var newValue = obj.value.replace(reg, "") - 0,
		deaultValue = eval(obj.id.replace(inputFlag,"")),
		slider = Ext.getCmp(sliderId),
		min = slider.minValue/100,
		max = slider.maxValue/100,
	    sliderValue = slider.getValue()/100;
		if(Math.abs(sliderValue*100 - deaultValue) >= 0.5){
			deaultValue = sliderValue;
			return false;
		}
		sliderValue = math.formatNumber(sliderValue,2);
		if (isNaN(newValue)) {
			tools.alertMsg("填写数据有误!只能是数字!请重新输入!");
			obj.focus();
			$(obj).val(sliderValue);
			return false;
		} else if (newValue < min) {
			tools.alertMsg("填写数据小于最小值,输入范围应在[" + min + "-" + max + "]之间!请重新输入!")
			obj.focus();
			$(obj).val(sliderValue);
			return false;
		} else if (newValue > max) {
			tools.alertMsg("填写数据大于最大值,输入范围应在[" + min + "~" + max + "]之间!请重新输入!")
			obj.focus();
			$(obj).val(sliderValue);
			return false;
		}else{
			// slider.setValue(newValue*100)
			// setDomValue(obj.id, newValue);
			 scope.module["datas"][sliderId] = newValue
			 updateInputValue(obj.id,newValue,datas);
		}
			return true;	
};
    function initInputEvent(datas){
    	//if(!scode)return ;
        $(".beforeInput>input").bind("change", function(event){
		 	 labelChange(this,datas);
		});
		 $(".beforeInput>input").focus(function(obj){
			var val = this.value.replace(reg,"");
			$(this).val(val);
		});
    }
    function onFailure(res){
         initRandomData();
         defaultsInit();
    };
     /**
     * 根据值大小更新progress
     */
    function updateProgressClass(obj,value){
        if(value>0){
        	obj.removeClass("red-progressBar");
			obj.addClass("progressBar");
		}else{
			obj.removeClass("progressBar");
		  	obj.addClass("red-progressBar");
		}
		$(".x-progress-bar").css("height","18px");
    }
    function varOperation(vars){
        if(vars.indexOf(vaprefix) != -1){
    	   vars = vars.replaceAll(vaprefix,vars);
    	}
    	return  "datas."+vars;
    }
    /**
     * 变量取值
     * vars 变量名称
     * bean 辅助对象
     * type 用来做为取数据用途的判断
     */
    function getVarEval(vars,bean,type){
    	try{
    	var value = 0;
    	 if(vars == "month"){
    	     tools.console(bean["sname"]+">>>>>有月份参数了!");
    	     //$("dd[name=month]>a").each(function(){});
    	 	 value = 3;//获取参数的方法之 后再补上吧！
    	 }else{
	    	 var datas = scope.module["datas"];
	    	  vars = varOperation(vars);
	    	   value = eval("("+vars+")");
	    	  var num = new Number(value);
	    	  value = num.toFixed(2);
	    	  if(bean && type > 2){//饼图时要给0的哦
	    	      if((value-0)<0){
	    	          tools.console(bean["label"]+"为负数==【"+value+"】为了图形的正常显示！负值为0了！");
	    	          value = 0.00;
	    	      }
	    	  }
	    	  if(value == undefined){
    	         tools.errorInfo("没有找到变量【"+vars+"】,故程序进行了错误的eval,请仔细检查！亲！");
    	      }
    	 }
	     return value;
    	}catch(e){
    	    tools.errorInfo("处理【"+vars+"】变量时出错\n"+e);
    	}
    }
    function setColorRangeValue(attr){
    	  var vars = attr["vars"];
    	  if(!vars) return ;
    	  var value = getVarEval(vars),
    	      industry = scope.module["industry"][vars];
    	  if(!industry){
    	     tools.alertMsg("没有定义变量为【"+vars+"】的 行业参数！请检查配制!");return ;
    	  }
    	  var coloRrangeColor = attr["colorrange"]["color"];
        for(var i = 0, len = coloRrangeColor.length;i<len;i++){
             var temp = coloRrangeColor[i];
             for(var key in temp){
             	     for(var ks in industry){
             	         if(temp[key] == ks){
                             temp[key] = industry[ks];
             	         }
             	     }
             }
         }
         var excellentValue = industry["excellent"],badValue = industry["bad"],sname = vars;
         if(industry["sname"]){
              sname = industry["sname"]+vars;
         }
         if(excellentValue <= badValue){
             tools.console("数据库里初始了错误的行业参数【"+sname+"】 最大值竟然小于最小值，有问题吗？请你确认！");
         }else{
               if(value >= excellentValue){
                   tools.console("行业参数【"+sname+"】=="+value+"大于优秀值【"+excellentValue+"】，故把它赋予优秀值了!");
                   value = excellentValue;
               }
               if(value <= badValue){
                    tools.console("行业参数【"+sname+"】=="+value+"小于最差值【"+badValue+"】，故把它赋予最差值了!");
                    value = badValue;
               }
         }
         attr["dials"]["dial"][0]["value"]  = value;
         attr["chart"]["upperlimit"]= excellentValue;
	     attr["chart"]["lowerlimit"]= badValue;
    }
    function varReplace(data,type){
       for(var j=0,lj=data.length;j<lj;j++){
	      	   data[j]["value"] = getVarEval(data[j]["vars"], data[j],type);
	    }
    }
    function convertObj(attr){
	      	  	  attr = attr.replaceAll(" ","");
	      return  eval("("+attr+")");//JSON.parse(attr)
    }
    /**
     * chart属性赋值
     * type=1  单值图
     * type=2  单系列数据图
     * type=3  多系列数据图   type不同 寻找data的位置也不同的哦！
     */
   function chartOperation(action,ff){
   	    var chartArr = scope.module["chart"];
   	    if(!chartArr) return ;
   	    var datas = scope.module["datas"];
	      for(var i = 0, len = chartArr.length;i<len;i++){
	      	   var attr = chartArr[i]["attr"];chartArr[i]["type"] = chartArr[i]["type"]-0;
	      	  if(typeof(attr) == "string"){
	      	  	  attr = convertObj(attr);
	      	  }
	      	  var type = chartArr[i]["type"];
	      	  attr["type"] = type;
	      	 
	      	  if(type == 1){
	      	   	   //还要给行业参数设置值呢colorrange
	      	   	   if(scope.module["industry"])setColorRangeValue(attr);
	      	   }else if(type == 2){
	      	      //var data = attr["data"];
	      	      /*for(var j=0,lj=data.length;j<lj;j++){
	      	         data[j]["value"] = getVarEval(data[j]["vars"], data[j],type);
	      	      }*/
	      	      varReplace(attr["data"],type);
	      	      var isShow = $("#"+attr["domId"]).parent().attr("isShow");
	      	      if(isShow){
		      	      if(isShow == "1"){
		      	         attr["chart"]["showlabels"] = 1;
		      	         attr["chart"]["showlegend"] = 1;
		      	      }else{
		      	         attr["chart"]["showlabels"] = 0;
		      	         attr["chart"]["showlegend"] = 0;
		      	      }
	      	      }
	      	   }else if(type ==3){
	      	   	 if(ff == true && type == 3){}else{
	      	        var dataset = attr["dataset"];
	      	       for(var oo=0,ll = dataset.length;oo<ll;oo++){
	      	           varReplace(dataset[oo]["data"],type);
	      	       }
	      	   	 }
	      	   	
	      	   }
	      	    chartArr[i]["attr"] = attr;
	      	 //if((ff==true || ff == "a") && type == 3){
	      	 	
	      	// }else{
	      	   createChart(action,attr);
	      	   tools.console("成功"+(action==true?"创建":"更新")+"了【"+attr["chart"]["caption"]+"】图！");
	      	 //}
	      	  
	      }
	    
    }
    function industryOperation(){
     	//var industry  = scope.module["industry"];
     	/*if(!industry)return;
     	for(var key in industry){
     		var arr = industry[key];
     	  if(arr instanceof Array){//说明是自己特定的
     	  	var obj={};
	     	    for(var i=0,len = arr.length;i<len;i++){
	     	    	  obj[arr[i]["id"]] = arr[i]["scode"]-0;
	     	    }
	     	    key = key.split("_")[0];
	     	    industry[key] = obj;
     		}else{//去数据库去查啦
     		    //var params = tools.getParams(DimArr);
     		}
     	}*/
     	for(var key in scope.module["industry"]){
     	    if(scope.module["industry"][key] == null){
     	    	delete  scope.module["industry"].key;
     	    }
     	}
     	//scope.module["industry"] = industry;
    };
    
    function commonHanlder(){
           setFormula();
           setAllProgressValue();
    	   setAllSliderValue();
           updateTipHtml();
    	   tools.console("【"+scope.module.title+"】看条件去update更新数据吧！亲！>>>>>>>>>>>>>>>>>>>>>>update");
    }
    function updateMoule(module){
          scope.module = module;
    	  scope.module["datas"] = initRandomData();
    	  commonHanlder();
    	  chartOperation(true);
    	  module["datas"] = scope.module["datas"];
    	   tools.unmask();
    }
    function updateDatas(datas,industry){
       scope.module["datas"] = datas;
       if(industry)scope.module["industry"] = industry;
       commonHanlder();
       var ff = getDbFlag();
       if(ff == true || ff == "a"){
           createIndustryTable(false);
       }else{
         chartOperation(false);
       }
       tools.unmask();
    }
      /**
   * 根据传过来的行业参数 与企业值  获取分数
   * 优秀值  excellent
   * 良好值  good
   * 平均值  average
   * 较低值  lowers
   * 较差值  bad
   */
  function getIndustryScoreByValue(inds,value){
  	 var result = 0,excellent = inds["excellent"],good = inds["good"],
  	 average = inds["average"],lowers = inds["lowers"],bad = inds["bad"];
  	 //两种情况，
  	 if(excellent > bad){
		  	 if(value >excellent){//大于优秀值给10分
		  	      result = 10
		  	 }else if(value == excellent){//等于优秀值给9分
		  	 	  result = 9;
		  	 }else if(excellent > value && value > good){//大于良好值并且小于优秀值给9分
		  	 	  result = 8;
		  	 }else if(value == good){//等于良好值给7分
		  	 	  result = 7;
		  	 }else if(good > value && value > average){//大于平均值并且小于良好值给6分
		  	 	  result = 6;
		  	 }else if(value == average){//等于平均值给5分
		  	 	  result = 5;
		  	 }else if(average > value && value > lowers){//大于平均值并且小于较低值给4分
		  	 	  result = 4;
		  	 }else if(value == lowers){//等于较低值给3分
		  	 	  result = 3;
		  	 }else if(lowers > value && value > bad){//大于较差值并且小于较低值给2分
		  	 	  result = 2;
		  	 }else if(value == bad){//等于较差值给1分
		  	 	  result = 1;
		  	 }else if(value < bad){//小于较差值给0分
		  	      result = 0;
		  	 }
  	 }else if(excellent < bad){
  	     if(value < excellent){//小于较差值给10分
		  	      result = 10
  	     }else if(value == excellent){//等于优秀值给9分
  	           result = 9;
  	     }else if(excellent < value && value < good){
		  	 	  result = 8;
	  	 }else if(value == good){
	  	 	  result = 7;
	  	 }else if(good < value && value < average){
	  	 	  result = 6;
	  	 }else if(value == average){
	  	 	  result = 5;
	  	 }else if(average < value && value < lowers){
	  	 	  result = 4;
	  	 }else if(value == lowers){
	  	 	  result = 3;
	  	 }else if(lowers < value && value < bad){
	  	 	  result = 2;
	  	 }else if(value == bad){
	  	 	  result = 1;
	  	 }else if(value > bad){
	  	      result = 0;
	  	 }
  	 }	  	 
  	 return result;
  }
   /* <tr >
		  <th>净资产收益率(%)</th>
		  <td >9</td>
		  <td >7</td>
		  <td >5</td>
		  <td >4</td>
		  <td >2</td>
		  <td class="good">7.12</td>
		  <td>6</td>
        </tr>
        data-toggle="modal" href="remote.html" data-target="#modal"
      */
    function getBootStrapRow(id,exp,vars,industry,action){
    	 tools.console(action==true?"创建":"更新"+"表格行："+industry["sname"]);
    	 var ff = scope.module["formula"][vars];
    	  var tr = "<tr ><th title=\""+ff["formula"]+"\">";
    	 if(ff["scode"]-0 != 0){
    	     tr += "<a query='indicator' indicator=\""+ff["scode"]+"\" exp=\""+ff["exp"]+"\"  id=\""+industry.id+"\"  href='javascript:;'>"+industry["sname"]+"</a>";
    	 }else{
    	    tr +=industry["sname"];
    	 }
	      tr += "</td><td>" +industry["excellent"]+"</td>";
	      tr += "<td>"+industry["good"]+"</td>";
	      tr += "<td>"+industry["average"]+"</td>";
	      tr += "<td>"+industry["lowers"]+"</td>";
	      tr += "<td>"+industry["bad"]+"</td>";
    	  var value = getVarEval(vars);
    	   var score = getIndustryScoreByValue(industry,value);
    	    tr += "<td>"+math.formatNumber(value,2)+"</td>";
    	    tr += "<td>"+score+"</td>";
    	    
    	    tr += "</tr>";
    	    $("#"+id+"Table").append(tr);
        return score;
    }
    function getBootStrapRowQypj(indsKey,exp,inds){
    	for(var key in inds){
    	    if(inds[key] != null && key.indexOf(indsKey) !=-1 && key.indexOf("-") != -1){
    	            var vars = key.split("-")[0];
    	            var value = getVarEval(vars),
    	            tempScode = getIndustryScoreByValue(inds[key],value);
    	            exp = exp.replaceAll(vars,tempScode);
    	    }
    	}
    	 var score  =  eval("("+exp+")");
        return score;
    }
    function getPjText(score){
       var text = "";
       if(score >= 9.5){
          text = "非常优秀【A++】";
       }else if(score >= 9.0 && score < 9.5){
          text = "很优秀【A+】";
       }else if(score >= 8.5 && score < 9.0){
          text = "优秀【A+】";
       }else if(score >= 8.0 && score < 8.5){
          text = "非常良好【B+】";
       }else if(score >= 7.5 && score < 8.0){
          text = "良好【B】";
       }else if(score >= 7.0 && score < 7.5){
          text = "较良好【B-】";
       }else if(score >= 6.0 && score < 7.0){
          text = "中等【C】";
       }else if(score >= 5.0 && score < 6.0){
          text = "较中等【C-】";
       }else if(score >= 4.0 && score < 5.0){
          text = "差【D】";
       }else if(score >= 2.0 && score < 4.0){
          text = "较差【E】";
       }else if(score <2.0){
          text = "很差【E-】";
       }
       return text;
    }
    function getDbFlag(){
       var id = scope.module["id"];
       if(id == "ylnl" || id == "fznl" || id == "yyzl" || id == "zwfx"){
         return true;
       }if(id == "qypj"){
         return "a";
       }
       return false;
    }
    function findChartByType(type){
         var chartArr = scope.module["chart"],arr = [];
         for(var i=0,len = chartArr.length;i<len;i++){
             if(chartArr[i]["type"]-0 == type){
                 arr.push(chartArr[i]);
             }
         }
         return arr;
    }
     function setChartByType(chart){
         for(var i=0,len = scope.module["chart"].length;i<len;i++){
             if((scope.module["chart"][i]["type"]-0) == (chart["type"] -0)){
             	 scope.module["chart"][i] = chart;
             }  
         }
     }
    function setDatas(data,key,score){
        for(var j=0,lj=data.length;j<lj;j++){
              if(data[j]["vars"] == key)
	      	   data[j]["value"] = score;
	     }
    }
    /**
     * 1  加减
     * 2  乘除
     */
//    function judgeFormulaType(exp){
//    	var bean = {};
//         if(exp.indexOf("/") != -1 || exp.indexOf("*") != -1){
//         	  bean["type"] = 2;
//         	  bean["text"] = "乘除";
//         }else{
//              bean["type"] = 1;
//         	  bean["text"] = "加减";
//         }
//         return bean;
//    }
    /**
     * 两个属性
     */
//    function createDrillTableBody(industry,bean){
//    	var category =[];
//    	for(var i=1;i<13;i++){
//    	  category.push({label:i+"月"});
//    	}
//    	var tr = "",categories = [{category:category}],dataset = [],color=["A66EDD","F6BD0F"],k=0,year = [];
//    	for(var key in bean){
//    	   tr+="<tr><th>"+key+"</th>";
//    	     var arr = bean[key],temp={seriesname:key,color:color[k]},data=[];
//    	      for(var i=0;i<12;i++){
//    	      	 var value = arr[i]["indicatorBean"]["datas"];
//    	      	 data.push({value:value});
//    	          tr+="<td title='"+arr[i]["indicatorBean"]["fun"]+"'>"+math.formatNumber(value,2)+"</td>";
//    	      }
//    	  year.push(key);
//    	   tr+="</tr>";
//    	   k++;
//    	   temp["data"] = data;
//    	   dataset.push(temp);
//    	}
//    	 var company = tools.getDimInfo("company"),title=industry.sname+"【"+company["value"][0]["name"]+year.join(",")+"】趋势分析";
//    	$("#drillLabel").text(title).attr("title",industry.formula);
//			  var styles={
//			    definition: [
//			      {
//			        name: "XScaleAnim",
//			        type: "ANIMATION",
//			        duration: 0.5,
//			        start: 0,
//			        param: "_xScale"
//			      },
//			      {
//			        name: "YScaleAnim",
//			        type: "ANIMATION",
//			        duration: 0.5,
//			        start: 0,
//			        param: "_yscale"
//			      },
//			      {
//			        name: "XAnim",
//			        type: "ANIMATION",
//			        duration: 0.5,
//			        start: 0,
//			        param: "_yscale"
//			      },
//			      {
//			        name: "AlphaAnim",
//			        type: "ANIMATION",
//			        duration: 0.5,
//			        start: 0,
//			        param: "_alpha"
//			      }
//			    ],
//			    application: [
//			      {
//			        toobject: "CANVAS",
//			        styles: "XScaleAnim, YScaleAnim,AlphaAnim"
//			      },
//			      {
//			        toobject: "DIVLINES",
//			        styles: "XScaleAnim,AlphaAnim"
//			      },
//			      {
//			        toobject: "VDIVLINES",
//			        styles: "YScaleAnim,AlphaAnim"
//			      },
//			      {
//			        toobject: "HGRID",
//			        styles: "YScaleAnim,AlphaAnim"
//			      }
//			    ]
//			  };
//	    var chartss =  {
//			    palette: 2,
//			    showvalues: 1,
//			    numvdivlines: 10,
//			    drawanchors: 0,
//			    divlinealpha: 30,
//			    alternatehgridalpha: 20,
//			    setadaptiveymin: 1,
//			    bordercolor:'dddddd',
//			    bgcolor:'FAF0E6',
//			    manageresize:1,
//			    decimals:2,
//			  //  chartBottomMargin:30,
//			    legendAllowDrag:1
//			  //  caption: industry.sname+"趋势拆线图"
//			  }
//			  //MSArea   MSLine
//    	var obj={flag:true,swf:"MSLine",domId:"rightChart",data:{styles:styles,chart:chartss,categories:categories,dataset:dataset}};
//    	$("#rightChart").empty()
//    	$("#drillTabelBody").empty().append(tr);
//    	$('#drill').modal('toggle');//toggle
//    	$("#drillBody").mask("正加载数据")
//    	 setTimeout(function(){
//    	    chart.createMultiSeriesChart(obj);
//    	    $("#drillBody").unmask()
//    	},100);
//    	tools.unmask();
//    	return tr;
//    }
    /**
     * 在这里ajax返回一个div填充的
     * $('#drill').modal('show');
     */
//    function updateModel(industry){
//       var bean = judgeFormulaType(industry.exp);
//       tools.mask();
//       function success(json){
//       	   tools.console(json);
//       	    createDrillTableBody(industry,json)
//       };
//       var params = tools.getDimParams();
//       params["type"] = bean.type;
//       params["indicator"] = industry["indicator"];
//       var url = tools.getBasePathUrl() +"dash/drill.cnbi";
//       tools.ajax({url : url,dataType :'json',async:false,data :params,success:success});
//    }
    function createIndustryTable(isAdd){
    	var flag = getDbFlag();
    	if(flag == true || flag == "a"){
    	var id = scope.module["id"],title=scope.module["title"],tips = title+"综合得分=="+scope.module["formula"][id]["formula"];
        if(isAdd == false){
          $("#"+id+"Table").empty();
         };
          var  inds = scope.module["industry"],
           chart = findChartByType(3)[0],
           attr =chart["attr"];
          if(typeof(attr) == "string"){
	      	  	  attr = convertObj(attr);
	      }
         var data = attr["dataset"][0]["data"];
          if(flag == true){
          	 var exp = scope.module["formula"][id]["exp"];//"jzcsyv*0.35+zzcbzv*0.25+xsmlrv*0.08+yyxjbzbs*0.08+cbfylrv*0.08+zbsyv*0.08+cbfze*0.08";
             for(var key in inds){
             	if(key.indexOf("_") == -1){
                  var score = getBootStrapRow(id,exp,key,inds[key],isAdd);
                    exp = exp.replaceAll(key,score);
	                 setDatas(data,key,score);
             	}
             }
             attr["dataset"][0]["data"] = data;
             chart["attr"] =attr;
             setChartByType(chart);
             exp = eval("("+exp+")");
             $("#"+id+"Table").append(" <tr title='"+tips+"'><th colspan=7>综合得分</th> <th>"+math.formatNumber(exp,2)+"</th></tr>");
             $("#"+id+"Table >tr>th>a").unbind();
    	     $("a[query=indicator]").click(function(){
    	    	Utils.updateModel({indicator:$(this).attr("indicator"),id:$(this).attr("id"),sname:$(this).text(),exp:$(this).attr("exp"),formula:$(this).parent().attr("title")});
    	    });
          }	
          if(flag == "a"){
          	  var resultExp = scope.module["formula"][id]["exp"],rowText =[];
             for(var key in inds){
             	if(key.indexOf("_") == -1 && key.indexOf("-") ==-1){
             		var industry = inds[key];
             		rowText.push(industry.sname);
                   var tr = "<tr><th><a href='javascript:alert(\"确定要看【"+industry["sname"]+industry["id"]+"】的趋势分析吗,时间不够，在开发中？\");'>"+industry["sname"]+"</a></th>";
	    	           tr += "<td>"+industry["excellent"]+"</td>";
	    	           tr += "<td>"+industry["good"]+"</td>";
	    	           tr += "<td>"+industry["average"]+"</td>";
	    	           tr += "<td>"+industry["lowers"]+"</td>";
	    	           tr += "<td>"+industry["bad"]+"</td>";
	    	      var exp = scope.module["formula"][key]["exp"];//"jzcsyv*0.35+zzcbzv*0.25+xsmlrv*0.08+yyxjbzbs*0.08+cbfylrv*0.08+zbsyv*0.08+cbfze*0.08";
                  var score = getBootStrapRowQypj(key,exp,inds);
	    	           tr += "<td>"+math.formatNumber(score,2)+"</td>";
	    	           tr += "<td>"+ getPjText(score-0)+"</td>";
	    	           $("#"+id+"Table").append(tr);
                       resultExp = resultExp.replaceAll(key,score);
                       scope.module["datas"][key] = score;
             	}
             }
              resultExp = eval("("+resultExp+")");
              var company = tools.getDimInfo("company"),
               year = tools.getDimInfo("year"),//company["value"][0]["name"]
               month = tools.getDimInfo("month"),
               text = getPjText(resultExp-0);
              $("#infomation").text(year["value"][0]["name"]+month["value"][0]["name"]+"月份按"+company["value"][0]["name"]+"的"+rowText.join(",")+rowText.length+"方面指标综合分析，给予公司在同行业中的整体评级为："+text);
              $("#"+id+"Table").append(" <tr title='"+tips+"'><th colspan=6>综合得分</th> <th>"+math.formatNumber(resultExp,2)+"</th><th>"+text+"</th></tr>");
          }
           chartOperation(isAdd,flag);
    	}
    }
    /**
     * 初始方法
     */
    function init(module){
    	try{
    	  scope.module = module;
    	  initRandomData();
    	  setFormula();
    	  industryOperation();
    	  createSlider();
    	  createProgress();
    	  initSliderEvent(module["slider"]);
    	  initInputEvent(module["datas"]);
    	  scope.module["load"] = 1;
    	  var ff = getDbFlag();
	       if(ff == true || ff == "a"){
	           createIndustryTable(true);
	       }else{
	         chartOperation(true);
	       }
	      updateTipHtml();
    	  module["datas"] = scope.module["datas"];
    	  tools.console("【"+module.title+"】成功初始了init所有可视化组件！>>>>>>>>>>>>>>>>>>>init");
    	  tools.unmask();
    	}catch(e){
    	  tools.errorInfo("初始【"+module["title"]+"】模型失败！"+e);
    	}
    	/* $("#definedDataApply").bind("click",function(){
    	     alert($(this).attr("id"));
    	 });*/
    }
  return {
    createProgress: createProgress,
    createSlider: createSlider,
    getValue: getValue,
    init:init,
    setFormula:setFormula,
    updateMoule:updateMoule,
    updateDatas:updateDatas
  }
});